package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.constant.SendMessageConstantModel;
import com.itheima.entity.Result;
import com.itheima.utils.TengXunMessageUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/validateCode")
public class validateCodeController {
    @Autowired
    private JedisPool jedisPool;
    /**
     * 发送验证码
     * /validateCode/send4Order.do?telephone=" + telephone
     */
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
//      1.发送短信
//         -1.1生成随机验证码
//        判断短信是否为空
        if (telephone.length()==0 && telephone==null){
             throw new RuntimeException("请输入正确的号码：");
        }
        String[] number=null;
        try{
            String vercode = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
            number=new String[]{vercode,"5"};
            TengXunMessageUtils.sendMessage(number, SendMessageConstantModel.ORDER_CHECKING, telephone);
        }catch (RuntimeException e){
            return new Result(false,e.getMessage());
        }
        catch (Exception e){
            return  new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        System.out.println("生成的随机验证码："+number[0]);
//        2.把验证码存贮到redis-- key=telephone+功能
        jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER, 500*60, number[0]);
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }

    /**  发出验证码
     * /validateCode/send4L0ogin.do?telephone="+telephone
     */
    @RequestMapping("/send4Login")
    public Result send4L0ogin(String telephone){
//         1.判断输入的随机验证码
        if (telephone==null || telephone.length()==0){
            throw new RuntimeException("请输入正确的号码");
        }
        String[]  number=null;
        try{
            //         2.发送短信
            String vercode=String.valueOf(ValidateCodeUtils.generateValidateCode(6));
            number=new String[]{vercode,"五"};
            TengXunMessageUtils.sendMessage(number,SendMessageConstantModel.ORDER_CHECKING,telephone);
        }catch (RuntimeException e){
            return new Result(false,e.getMessage());
        }catch (Exception e){
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        System.out.println("生成的登陆密码为："+number[0]);
        jedisPool.getResource().setex(telephone+RedisMessageConstant.SENDTYPE_LOGIN,500*60 , number[0]);
        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
